let { Service } = require('egg')
const { mysql } = require('../../config/plugin')
const getStartTime = require('../utils/getStartTime.js')

class HomeService extends Service {
    async getCount(){
        let {mysql} = this.app
        let obj = {}
        // 获取所有用户数量
        let sql1 = 'select count(*) users from user where roleId  !=0'
        let userRes = await mysql.query(sql1)
        let userCount = userRes[0].users
        obj.userCount = userCount
        // 获取实验室数量
        let sql2 = 'select count(*) labs from laboratory'
        let labRes = await mysql.query(sql2)
        let  labCount = labRes[0].labs
        obj.labCount = labCount

        //  获取实验室动态数量
        let  sql3 = 'select count(*) trends from trends'
        let treRes = await mysql.query(sql3)
        let trendsCount = treRes[0].trends
        obj.trendsCount = trendsCount

        // 获取预约当前未过期的预约申请数量
        let  sql4 = 'select * from reservation'
        let resList = await mysql.query(sql4)
        let arr = [...resList]
        let resCount = 0
        for(let i=0;i<arr.length;i++){
            let res1 = await mysql.get('daytime',{timeId:arr[i].dayTimeId})
            let  dateTime = res1.dateTime

            let sql = 'select start from timeoption where timeId in (select  timeOpId from daytime where timeId in (select dayTimeId from  reservation where reservationId = ?))'
            let res2 = await mysql.query(sql,[arr[i].reservationId])
        
            
          if(res2[0]){

            let start = res2[0].start
         
            let time1=  getStartTime(start,dateTime)
            let nowTime = new Date().getTime()
            if(arr[i].status==1){
              if(nowTime<time1){
               
                resCount=resCount+1
                arr[i].isExpire =true
              }else{
                arr[i].isExpire =false
              }
                
            }
          }


        }
        obj.resCount = resCount
      
     return obj
    }
}

module.exports = HomeService